import config from '../config/index.js';

const API_BASE = config.API_BASE_URL;

class AuthAPI {
  constructor() {
    this._isLoggedIn = false;
    this._currentUser = null;
    this._listeners = [];
    this._initialized = false;
    
    // 初始化时检查本地存储的token
    this.initializeFromStorage().catch(error => {
      console.error('初始化认证状态失败:', error);
    });
  }
  
  // 从本地存储初始化用户状态
  async initializeFromStorage() {
    const token = localStorage.getItem('auth_token');
    if (token) {
      try {
        // 如果有token，尝试获取用户信息
        const result = await this.getProfile();
        if (result.success) {
          this._isLoggedIn = true;
          this._currentUser = result.user;
          this.notifyListeners();
        } else {
          // 如果token无效，清除本地存储
          localStorage.removeItem('auth_token');
          this._isLoggedIn = false;
          this._currentUser = null;
        }
      } catch (error) {
        // 如果获取用户信息失败，清除本地存储
        console.error('初始化用户状态失败:', error);
        localStorage.removeItem('auth_token');
        this._isLoggedIn = false;
        this._currentUser = null;
      }
    } else {
      this._isLoggedIn = false;
      this._currentUser = null;
    }
  }

  addListener(callback) {
    this._listeners.push(callback);
  }

  removeListener(callback) {
    const index = this._listeners.indexOf(callback);
    if (index > -1) {
      this._listeners.splice(index, 1);
    }
  }

  notifyListeners() {
    this._listeners.forEach(callback => callback(this._currentUser, localStorage.getItem('auth_token')));
  }

  getAuthHeaders() {
    const token = localStorage.getItem('auth_token');
    return {
      'Content-Type': 'application/json',
      'Authorization': token ? `Bearer ${token}` : ''
    };
  }

  async login(username, password) {
    try {
      const response = await fetch(`${API_BASE}/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });

      const data = await response.json();
      
      if (data.success) {
        localStorage.setItem('auth_token', data.token);
        this._isLoggedIn = true;
        this._currentUser = data.user;
        
        // 🎯 关键新增：根据用户角色设置系统角色类型
        const { setUserRole } = await import('./userStorage');
        if (data.user && (data.user.role === 'admin' || data.user.role === 'storyteller')) {
          console.log('🎭 管理员/说书人登录，设置为storyteller角色');
          setUserRole('storyteller');
        } else if (data.user) {
          console.log('👤 普通用户登录，设置为storyteller角色（管理角色）');
          setUserRole('storyteller'); // 暂时都设为storyteller，避免数据清空
        }
        
        this.notifyListeners();
      }
      
      return data;
    } catch (error) {
      console.error('登录失败:', error);
      return { success: false, error: '网络错误，请重试' };
    }
  }

  async register(username, password) {
    try {
      const response = await fetch(`${API_BASE}/auth/register`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, password })
      });

      const data = await response.json();
      
      if (data.success) {
        localStorage.setItem('auth_token', data.token);
        this._isLoggedIn = true;
        this._currentUser = data.user;
        this.notifyListeners();
      }
      
      return data;
    } catch (error) {
      console.error('注册失败:', error);
      return { success: false, error: '网络错误，请重试' };
    }
  }

  async logout() {
    try {
      const response = await fetch(`${API_BASE}/auth/logout`, {
        method: 'POST',
        headers: this.getAuthHeaders()
      });

      const data = await response.json();
      
      localStorage.removeItem('auth_token');
      this._isLoggedIn = false;
      this._currentUser = null;
      
      // 清除角色缓存
      const { clearRoleCache } = await import('./userStorage');
      clearRoleCache();
      console.log('✅ 登出成功，已清除角色缓存');
      
      this.notifyListeners();
      
      return data;
    } catch (error) {
      console.error('登出失败:', error);
      // 即使网络请求失败，也要清除本地状态
      localStorage.removeItem('auth_token');
      this._isLoggedIn = false;
      this._currentUser = null;
      
      // 清除角色缓存
      const { clearRoleCache } = await import('./userStorage');
      clearRoleCache();
      console.log('✅ 登出成功，已清除角色缓存');
      
      this.notifyListeners();
      return { success: true };
    }
  }

  async getProfile() {
    try {
      const response = await fetch(`${API_BASE}/auth/profile`, {
        method: 'GET',
        headers: this.getAuthHeaders()
      });

      const data = await response.json();
      
      if (data.success) {
        this._currentUser = data.user;
        this._isLoggedIn = true;
      } else {
        this._isLoggedIn = false;
        this._currentUser = null;
        localStorage.removeItem('auth_token');
      }
      
      return data;
    } catch (error) {
      console.error('获取用户信息失败:', error);
      this._isLoggedIn = false;
      this._currentUser = null;
      localStorage.removeItem('auth_token');
      return { success: false, error: '网络错误，请重试' };
    }
  }

  async ensureInitialized() {
    if (!this._initialized) {
      await this.initializeFromStorage();
      this._initialized = true;
    }
  }

  async isLoggedIn() {
    await this.ensureInitialized();
    return this._isLoggedIn;
  }

  async getCurrentUser() {
    await this.ensureInitialized();
    return this._currentUser;
  }

  async isAdmin() {
    await this.ensureInitialized();
    return this._currentUser && this._currentUser.role === 'admin';
  }

  hasPermission(permission) {
    if (!this._currentUser) return false;
    
    // 管理员拥有所有权限
    if (this._currentUser.role === 'admin') return true;
    
    // 检查用户自定义权限
    if (this._currentUser.permissions && this._currentUser.permissions.includes(permission)) {
      return true;
    }
    
    return false;
  }

  async refreshToken() {
    try {
      const response = await fetch(`${API_BASE}/auth/refresh`, {
        method: 'POST',
        headers: this.getAuthHeaders()
      });

      const data = await response.json();
      
      if (data.success) {
        localStorage.setItem('auth_token', data.token);
      }
      
      return data;
    } catch (error) {
      console.error('刷新Token失败:', error);
      return { success: false, error: '网络错误，请重试' };
    }
  }

  async getRegistrationStatus() {
    try {
      const response = await fetch(`${API_BASE}/system/registration`, {
        method: 'GET',
        headers: this.getAuthHeaders()
      });

      const data = await response.json();
      return data.success ? data.enabled : true;
    } catch (error) {
      console.error("获取注册状态失败:", error);
      return true; // 默认允许注册
    }
  }

  async getAllUsers() {
    try {
      const response = await fetch(`${API_BASE}/auth/users`, {
        method: "GET",
        headers: this.getAuthHeaders(),
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("获取用户列表失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  async updateUserPermissions(userId, permissions) {
    try {
      const response = await fetch(`${API_BASE}/auth/users/${userId}/permissions`, {
        method: "PUT",
        headers: this.getAuthHeaders(),
        body: JSON.stringify({ permissions })
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("更新用户权限失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  async toggleRegistration() {
    try {
      const response = await fetch(`${API_BASE}/system/registration`, {
        method: "PUT",
        headers: this.getAuthHeaders(),
        body: JSON.stringify({ enabled: true }),
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("切换注册状态失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  async changeUserRole(userId, newRole) {
    try {
      const response = await fetch(`${API_BASE}/auth/users/${userId}/role`, {
        method: "PUT",
        headers: this.getAuthHeaders(),
        body: JSON.stringify({ role: newRole }),
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("更改用户角色失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  async deleteUser(userId) {
    try {
      const response = await fetch(`${API_BASE}/auth/users/${userId}`, {
        method: "DELETE",
        headers: this.getAuthHeaders(),
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("删除用户失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  // 创建新用户（管理员功能）
  async createUser(userData) {
    try {
      const response = await fetch(`${API_BASE}/auth/users`, {
        method: "POST",
        headers: this.getAuthHeaders(),
        body: JSON.stringify(userData)
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("创建用户失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  // 更新用户信息（管理员功能）
  async updateUser(userId, userData) {
    try {
      const response = await fetch(`${API_BASE}/auth/users/${userId}`, {
        method: "PUT",
        headers: this.getAuthHeaders(),
        body: JSON.stringify(userData)
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("更新用户失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  // 获取单个用户详情（管理员功能）
  async getUserById(userId) {
    try {
      const response = await fetch(`${API_BASE}/auth/users/${userId}`, {
        method: "GET",
        headers: this.getAuthHeaders(),
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("获取用户详情失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  // 批量删除用户（管理员功能）
  async batchDeleteUsers(userIds) {
    try {
      const response = await fetch(`${API_BASE}/auth/users/batch`, {
        method: "DELETE",
        headers: this.getAuthHeaders(),
        body: JSON.stringify({ userIds })
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("批量删除用户失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }

  // 批量更新用户角色（管理员功能）
  async batchUpdateUserRoles(userIds, role) {
    try {
      const response = await fetch(`${API_BASE}/auth/users/batch/role`, {
        method: "PUT",
        headers: this.getAuthHeaders(),
        body: JSON.stringify({ userIds, role })
      });

      const data = await response.json();
      return data;
    } catch (error) {
      console.error("批量更新用户角色失败:", error);
      return { success: false, error: "网络错误，请重试" };
    }
  }
}

export default new AuthAPI(); 